// order.js
const request = require('../../utils/request.js');
const util = require('../../utils/util.js');

Page({
  data: {
    address: null,
    cart: [],
    merchantInfo: {},
    totalPrice: '0.00',
    discount: '0.00',
    actualPrice: '0.00',
    remark: ''
  },

  onLoad: function(options) {
    // 获取传递的价格参数
    const { totalPrice, discount } = options;
    
    // 获取商家信息
    const app = getApp();
    const merchantInfo = app.globalData.selectedMerchant;
    const cart = app.globalData.cart || [];
    
    // 计算实际支付金额
    const actualPrice = util.formatPrice(parseFloat(totalPrice) - parseFloat(discount || 0));
    
    this.setData({
      merchantInfo,
      cart,
      totalPrice,
      discount: discount || '0.00',
      actualPrice
    });
    
    // 加载默认地址
    this.loadDefaultAddress();
  },

  onShow: function() {
    // 页面显示时重新加载地址（处理从地址选择页返回的情况）
    if (this.data.addressId) {
      this.loadAddressById(this.data.addressId);
    }
  },

  // 加载默认地址
  loadDefaultAddress: function() {
    const app = getApp();
    const userId = app.globalData.userInfo.user_id;
    
    request.get('/api/address/list', { userId }).then(res => {
      if (res.success && res.data.length > 0) {
        // 查找默认地址
        const defaultAddress = res.data.find(addr => addr.is_default === 1);
        
        // 如果有默认地址则使用，否则使用第一个地址
        this.setData({
          address: defaultAddress || res.data[0]
        });
      }
    });
  },

  // 根据ID加载地址
  loadAddressById: function(addressId) {
    const app = getApp();
    const userId = app.globalData.userInfo.user_id;
    
    request.get('/api/address/list', { userId }).then(res => {
      if (res.success && res.data.length > 0) {
        const address = res.data.find(addr => addr.address_id === parseInt(addressId));
        if (address) {
          this.setData({ address });
        }
      }
    });
  },

  // 选择地址
  selectAddress: function() {
    wx.navigateTo({
      url: '/pages/address/address?select=true'
    });
  },

  // 备注输入
  onRemarkInput: function(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 提交订单
  submitOrder: function() {
    const { address, cart, totalPrice, discount, remark } = this.data;
    const app = getApp();
    
    // 验证地址
    if (!address) {
      request.showError('请选择收货地址');
      return;
    }
    
    // 验证购物车
    if (cart.length === 0) {
      request.showError('购物车为空');
      return;
    }
    
    // 准备订单数据
    const orderData = {
      userId: app.globalData.userInfo.user_id,
      merchantId: app.globalData.selectedMerchant.merchant_id,
      totalPrice: parseFloat(totalPrice) - parseFloat(discount),
      addressId: address.address_id,
      remark,
      items: cart.map(item => ({
        dishId: item.dish_id,
        dishName: item.name,
        price: item.price,
        quantity: item.quantity
      }))
    };
    
    // 提交订单
    request.post('/api/order/create', orderData).then(res => {
      if (res.success) {
        // 清空购物车
        app.globalData.cart = [];
        
        // 提示成功
        wx.showToast({
          title: '下单成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            // 跳转到订单详情页
            setTimeout(() => {
              wx.redirectTo({
                url: `/pages/order-detail/order-detail?orderId=${res.data.order_id}`
              });
            }, 2000);
          }
        });
      } else {
        request.showError('下单失败，请重试');
      }
    }).catch(() => {
      request.showError('下单失败，请重试');
    });
  }
});